<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import { queryAllHouseholdersService, deleteHouseholderService, queryHouseholderService, updateHouseholderInfoService, addHouseholderInfoService } from '@/api/householder.js'

//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(8)//每页条数
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    pageSize.value = size
    queryAllHouseholders()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    pageNum.value = num
    queryAllHouseholders()
}

const householderCard = ref('')
const householdersInfo = ref([])
const selectedHouseholder = ref(null)
//查询所有用户
const queryAllHouseholders = async () => {
    let result = await queryAllHouseholdersService(pageNum.value, pageSize.value)
    if (result.code === 200) {
        householdersInfo.value = result.data.householdersQueryVos
        total.value = result.data.total
    } else {
        ElMessage.error('服务异常!')
    }

}
queryAllHouseholders()

//根据身份证号码查询用户
const queryHouseholder = async () => {
    let result = await queryHouseholderService(householderCard.value)
    if (result.code === 200) {
        // 清空当前数据，只显示查询结果
        householdersInfo.value = [result.data]  // 假设返回的是单个住户信息
        console.log(result.data)
    } else {
        ElMessage.error('服务异常!')
    }
}

//控制抽屉是否显示
const visibleDrawer = ref(false)
const title = ref('')
const buttonText = ref('')
//点击添加新住户的时候，抽屉弹出，并修改标题和清除回显的数据
const clearData = () => {
    visibleDrawer.value = true
    title.value = '添加新住户'
    buttonText.value = '添加'
    selectedHouseholder.value = {
        householderName: '',
        householderPhone: '',
        householderCard: '',
        householderPhoto: '',
        carLicensePlate: '',
        householderId: null
    }
}

const showDrawer = (row) => {
    visibleDrawer.value = true
    title.value = '修改住户信息'
    buttonText.value = '修改'
    //控制抽屉的显示和数据的回显
    selectedHouseholder.value = {
        householderName: row.householderName,
        householderPhone: row.householderPhone,
        householderCard: row.householderCard,
        householderPhoto: row.householderPhoto,
        carLicensePlate: row.carLicensePlate,
        //修改的时候必须传递一个ID
        householderId: row.householderId
    }
}

const updateHouseholderInfo = async () => {
    let result = await updateHouseholderInfoService(selectedHouseholder.value)
    if (result.code === 200) {
        ElMessage.success('修改成功!')
        queryAllHouseholders()
        visibleDrawer.value = false
    } else {
        ElMessage.error('修改失败!')
    }
}

const addHouseholderInfo = async () => {
    let result = await addHouseholderInfoService(selectedHouseholder.value)
    if (result.code === 200) {
        ElMessage.success('添加成功!')
        queryAllHouseholders()
        visibleDrawer.value = false
    } else {
        ElMessage.error('添加失败!')
    }
}

const deleteHouseholder = async (row) => {
    ElMessageBox.confirm(
        '您确认要删除吗?',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteHouseholderService(row.householderId)
            if (result.code === 200) {
                ElMessage.success('删除成功!')
                //重新获取列表
                queryAllHouseholders()
            } else {
                ElMessage.error('删除失败!')
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

const rules = {
    householderName: [
    { required: true, message: '请输入名字', trigger: 'blur' },
    {
      pattern: /^.{1,15}$/,
      message: '姓名需在1到15个字符之间!',
      trigger: 'blur'
    }
  ],
  householderPhone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    {
      // 匹配中国大陆手机号码（11位数字，前三位匹配已知的手机号段）
      // 匹配香港和澳门电话号码（通常以852或853开头，后跟7位或8位数字）
      pattern: /^(1[3456789]\d{9}|852\d{8}|853\d{8})$/,
      message: '请输入正确的电话号码！',
      trigger: 'blur'
    }
  ],
  householderCard: [
    { required: true, message: '请输入身份证号码', trigger: 'blur' },
    {
      pattern: /^\d{6}(19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/,
      message: '请输入正确的身份证号码！',
      trigger: 'blur'
    }
  ],
  carLicensePlate: [
    { required: false, message: '请输入车牌号', trigger: 'blur' },
    {
      pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[\dA-HJ-NP-Za-hj-np-z]{4,6}$/,
      message: '请输入正确的车牌号！',
      trigger: 'blur'
    }
  ],
}

</script>

<template>
    <el-form label-width="auto" class="searchStyle">
        <el-space fill>
            <el-form-item label="身份证号码" style="min-width: 400px">
                <el-input v-model="householderCard" />
            </el-form-item>
        </el-space>
        <el-form-item>
            <el-button type="primary" @click="queryHouseholder">搜索</el-button>
            <el-button @click="householderCard = ''; queryAllHouseholders()">重置</el-button>
            <el-button color="#626aef" :dark="isDark" @click="clearData">添加新住户</el-button>
        </el-form-item>

    </el-form>

    <!-- 表格 -->
    <div style="width: 100%;height: 400px;">
        <el-table :data="householdersInfo" stripe style="width: 100%;">
            <el-table-column prop="householderName" label="姓名" width="100" />
            <el-table-column prop="householderPhone" label="电话" width="180" />
            <el-table-column prop="householderCard" label="身份证号码" width="200" />
            <el-table-column prop="householderPhoto" label="照片" width="500" />
            <el-table-column prop="carLicensePlate" label="车牌" width="160" />

            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Edit" circle @click="showDrawer(row)" />
                    <el-button type="danger" :icon="Delete" circle @click="deleteHouseholder(row)" />
                </template>
            </el-table-column>

        </el-table>

    </div>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 8]"
        layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
        @current-change="onCurrentChange" style="margin-top: 8%; justify-content: flex-end" />


    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
        <!-- 添加新住户 -->
        <el-form :model="selectedHouseholder" :rules="rules" label-width="100px">
            <el-form-item label="名字" prop="householderName">
                <el-input v-model="selectedHouseholder.householderName" placeholder="请输入名字"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="householderPhone">
                <el-input v-model="selectedHouseholder.householderPhone" placeholder="请输入电话"></el-input>
            </el-form-item>
            <el-form-item label="身份证号码" prop="householderCard">
                <el-input v-model="selectedHouseholder.householderCard" placeholder="请输入身份证号码"></el-input>
            </el-form-item>
            <el-form-item label="照片">
                <el-input v-model="selectedHouseholder.householderPhoto" placeholder="请去录入人脸" disabled></el-input>
            </el-form-item>
            <el-form-item label="车牌号" prop="carLicensePlate">
                <el-input v-model="selectedHouseholder.carLicensePlate" placeholder="请输入车牌号"></el-input>
            </el-form-item>


            <el-form-item>
                <el-button style="width: 100px;" type="primary"
                    @click="title == '修改住户信息' ? updateHouseholderInfo() : addHouseholderInfo()">{{ buttonText
                    }}</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>

</template>

<style scoped>
.searchStyle {
    display: flex;
    justify-content: left;
}

.searchStyle .el-form-item {
    margin-left: 5%;
}
</style>
